<template>
  <div>
    <table-ext :columns="columns" :searchForm="searchForm" :config="config" ref="tableExt" @checkedData="getCheckedData">
       <template slot="table-action">
          <el-button type="primary" @click="rematch()" icon="el-icon-plus">匹配框架</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="addToEnquiry()">加入处理清单</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="openPendingDialog()">待处理清单({{this.pendingCount}})</el-button>
          <!-- <div style="margin-left: 10px;">
            <el-dropdown split-button type="primary" @command="handleClick">
              更多操作
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">订单</el-dropdown-item>
                <el-dropdown-item command="2">询价</el-dropdown-item>
                <el-dropdown-item command="3">招标</el-dropdown-item>
                <el-dropdown-item command="4">认证</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div> -->
          <!-- <el-button type="primary" @click="openCloseDialog()" icon="el-icon-delete">关闭</el-button> -->
          <!-- <el-button type="primary" @click="rematch()" icon="el-icon-plus">匹配框架</el-button>
          <el-button type="primary" @click="toEnquiry()" icon="el-icon-plus">转询价</el-button>
          <el-button type="primary" @click="toBid()" icon="el-icon-plus">转询价</el-button>
          <el-button type="primary" @click="toNpcTask()" icon="el-icon-plus">转询价</el-button> -->
       </template>
    </table-ext>
    <el-dialog title="关闭采购申请" :visible="dialogVisible" width="800px">
      <el-form :model="closeForm" ref="closeForm">
        <el-form-item label="关闭原因：" prop="reason">
          <el-input type="textarea" v-model="closeForm.reason"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closePrItem()">提交</el-button>
        <el-button @click="cancleDialog('closeForm')">取消</el-button>
      </div>
    </el-dialog>
    <!-- 待处理对话框 -->
    <el-dialog title="待处理清单" :visible.sync="pendingVisible" width="60%" :default-sort="{prop: 'itemNo', order: 'descending'}" @checkedData="getCheckedData">
      <div style="float: right;margin-bottom: 5px;">
        <el-dropdown split-button type="primary" @command="handleClick">
          更多操作
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">订单</el-dropdown-item>
            <el-dropdown-item command="2">询价</el-dropdown-item>
            <el-dropdown-item command="3">招标</el-dropdown-item>
            <el-dropdown-item command="4">认证</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-table :data="pendingData" border>
        <el-table-column type="selection" align="center" width="50"></el-table-column>
        <el-table-column label="序号" align="center" width="60">
            <template slot-scope="scope">
              {{scope.$index + 1}}
            </template>
          </el-table-column>
        <el-table-column prop="prNo" align="center" label="申请单号" width="150"></el-table-column>
        <el-table-column prop="itemNo" align="center" label="行号" width="90"></el-table-column>
        <el-table-column prop="factoryName" align="center" label="工厂" width="200"></el-table-column>
        <el-table-column prop="materialCode" align="center" label="物料编码" width="150"></el-table-column>
        <el-table-column prop="materialName" align="center" label="物料描述" width="300"></el-table-column>
        <el-table-column prop="purUnitName" align="center" label="单位" width="90"></el-table-column>
        <el-table-column prop="purchaseQty" align="center" label="需求数量" width="120"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
  import TableExt from '@/components/common/table-ext/table-ext.vue';
  import TableIcon from '@/components/common/table-ext/table-icon';
 import axios  from 'axios'
  export default {
    // 引入自定义表格组件
    components:{
      'table-ext': TableExt
    },
    data() {
      return {
        // 声明一个有效的id数组集合
        selectedIdArry:[],
        materialData:[], // 发起询价、招标、认证匹配的物料数据
        vendorData:[], // 发起询价、招标、认证匹配的供应商数据
        pendingCount:null,
        pendingVisible:false,
        pendingData:[],
        dialogVisible:false,
        // 关闭表单对象
        closeForm:{
          reason:'',
          ids:[]
        },
        // 选中的数据
        checkedData:[],
        config:{ // 页面共通配置
          title: '采购申请明细', 
          isPage: true,
          isNo: true,
          selection: true,
          crudMapping:{
            query:{
              url: this.lib.config.host.prModule + "/purchaserequest/item/query",
            }
          }
        },
        // 查询表单配置
        searchForm:[{
          label: '采购组织:',
          key: 'orgId',
          type: 'select',
          dict: {
            url: this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getPurOrgByUserId/' + this.getCurrUserId(),
            method: 'get',
            label: 'purOrgName',
            value: 'id'
          }
        },{
          label: '采购组:',
          key: 'groupId',
          type: 'select',
          dict: {
            url: this.lib.config.host.masterData + '/mdata/purOrgMgt/purGroup/getByPurOrgId/{orgId}',
            method: 'post',
            label: 'purGroupName',
            value: 'id'
          }
        },{
          label: '工厂:',
          key: 'factoryId',
          type: 'select',
          dict: {
            url:  this.lib.config.host.masterData + '/system/factoryMgt/factorys/getFactoryByPurId/{orgId}',
            method: 'post',
            label: 'factoryName',
            value: 'factoryId'
          }
        },{
          label: '单据号:',
          key: 'prNo ',
          type: 'input'
        },{
          label: '物料:',
          key: 'materialName',
          type: 'input'
        },{
          label: '申请类型:',
          key: 'erpTypeNo',
          type: 'input'
        },{
          label: '申请人:',
          key: 'applyerName',
          type: 'input'
        },{
          label: '处理人:',
          key: 'handleUserName',
          type: 'input'
        },{
          label: '处理状态:',
          key: 'handleStatus',
          type: 'select',
          dict: [{
            key: '0',
            value: '未处理'
          },{
            key: '1',
            value: '已处理'
          }]
        },{
          label: '匹配状态:',
          key: 'frameworkAgrStatus',
          type: 'select',
          dict: [{
            key: '0',
            value: '无效'
          },{
            key: '1',
            value: '有效'
          }]
        },{
          label: '询价状态:',
          key: 'enquiryStatus',
          type: 'select',
          dict: [{
            key: '0',
            value: '未询价'
          },{
            key: '1',
            value: '已定价'
          },{
            key: '2',
            value: '询价中'
          }]
        },{
          label: '合同状态:',
          key: 'contractStatus',
          type: 'select',
          dict: [{
            key: '0',
            value: '未开始'
          },{
            key: '1',
            value: '已签订'
          },{
            key: '2',
            value: '签订中'
          }]
        },{
          label: '合同执行状态:',
          key: 'contractExStatus',
          type: 'select',
          dict: [{
            key: '0',
            value: '未执行'
          },{
            key: '1',
            value: '已执行'
          },{
            key: '2',
            value: '部分执行'
          }]
        },{
          label: '下单状态:',
          key: 'orderStatus',
          type: 'select',
          dict: [{
            key: '0',
            value: '未下单'
          },{
            key: '1',
            value: '已下单'
          },{
            key: '2',
            value: '部分下单'
          }]
        }],
        // 表格列定义
        columns:[{
          label: '采购组织ID',
          key: 'purOrgId',
          align: 'center',
          width:'150px',
          hidden:true
        },
        {
          label: '采购组织编码',
          key: 'purOrgCode',
          align: 'center',
          width:'150px',
          hidden:true
        },
        {
          label: '采购组织',
          key: 'purOrgName',
          align: 'center',
          width:'150px',
          hidden:true
        },{
          label: '工厂',
          key: 'factoryName',
          align: 'center',
          width:'150px'
        },{
          label: '采购组',
          key: 'purGroupName',
          align: 'center',
          width:'200px'
        },{
          label: '单据编号',
          key: 'prNo',
          align: 'center',
          width:'200px'
        },{
          label: '行号',
          key: 'itemNo',
          align: 'center',
          width:'100px'
        },{
          label: '物料编码',
          key: 'materialCode',
          align: 'center',
          width:'200px'
        },{
          label: '物料描述',
          key: 'materialName',
          align: 'center',
          width:'200px'
        },{
          label: '需求数量',
          key: 'purchaseQty',
          align: 'center',
          width:'100px'
        },{
          label: '单位',
          key: 'purUnitName',
          align: 'center',
          width:'100px'
        },{
          label: '申请类型',
          key: 'erpTypeNo',
          align: 'center',
          width:'150px'
        },{
          label: '物料组',
          key: 'matGroupName',
          align: 'center',
          width:'200px'
        },{
          label: '交货时间',
          key: 'deliveryDate',
          align: 'center',
          width:'150px'
        },{
          label: '申请人',
          key: 'applyerName',
          align: 'center',
          width:'150px'
        },{
          label: '发布状态',
          key: 'publishStatus',
          align: 'center',
          width:'100px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
                flag: params.row.publishStatus,
                titles: [{status:0,title:'未发布'},{status:1,title:'已发布'}]
            }});
          }
        },{
          label: '发布时间',
          key: 'publishTime',
          align: 'center',
          width:'150px'
        },{
          label: '审核状态',
          key: 'checkStatus',
          align: 'center',
          width:'150px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
                flag: params.row.checkStatus,
                titles: [{status:0,title:'未开始'},{status:1,title:'通过'},{status:3,title:'待审核'},{status:-1,title:'驳回'}]
            }});
          }
        },{
          label: '审核日期',
          key: 'checkTime',
          align: 'center',
          width:'150px'
        },{
          label: '内部订单号',
          key: 'innerOrderNo',
          align: 'center',
          width:'150px'
        },{
          label: '成本中心',
          key: 'costCenter',
          align: 'center',
          width:'200px'
        },{
          label: '资产号',
          key: 'assetNo',
          align: 'center',
          width:'200px'
        },{
          label: '是否预算',
          key: 'budgetFlag',
          align: 'center',
          width:'200px'
        },{
          label: '处理状态',
          key: 'handleStatus',
          align: 'center',
          width:'100px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
              flag: params.row.confirmStatus,
              titles: [{status:0,title:'未处理'},{status:1,title:'已处理'},{status:-1,title:'已关闭'}]
            }});
          }
        },{
          label: '处理人',
          key: 'handleUserName',
          align: 'center',
          width:'150px'
        },{
          label: '匹配状态',
          key: 'frameworkAgrStatus',
          align: 'center',
          width:'100px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
              flag: params.row.frameworkAgrStatus,
              titles: [{status:0,title:'无效'},{status:1,title:'有效'}]
            }});
          }
        },{
          label: '下单状态',
          key: 'orderStatus',
          align: 'center',
          width:'100px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
              flag: params.row.orderStatus,
              titles: [{status:0,title:'未下单'},{status:1,title:'已下单'},{status:2,title:'部分下单'}]
            }});
          }
        },{
          label: '询价状态',
          key: 'enquiryStatus',
          align: 'center',
          width:'100px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
                flag: params.row.enquiryStatus,
                titles: [{status:0,title:'未询价'},{status:1,title:'已定价'},{status:2,title:'询价中'}]
            }});
          }
        },{
          label: '合同状态',
          key: 'contractStatus',
          align: 'center',
          width:'100px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
              flag: params.row.contractStatus,
              titles: [{status:0,title:'未开始'},{status:1,title:'已签订'},{status:2,title:'签订中'}]
            }});
          }
        },{
          label: '合同执行状态',
          key: 'contractExStatus',
          align: 'center',
          width:'150px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
              flag: params.row.contractExStatus,
              titles: [{status:0,title:'未执行'},{status:1,title:'已执行'},{status:2,title:'执行中'}]
            }});
          }
        },{
          label: '备注',
          key: 'remarks',
          align: 'center',
          width:'300px',
        }]
      };
    },
    mounted() {
        console.log(this.axios.all)
        console.log(axios.all)
       //this.initData();
    },
    methods: {
      initData(){
        // 获取采购组织
        this.getSelectData('get', this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getPurOrgByUserId/' + this.getCurrUserId(), {}, 'id', 'purOrgName').then((data)=>{
            this.purOrgOptions = data;
        });
      },
      // 采购组织在改变的时候查询采购组
      handleChange(value) {
        // 获取srm采购组
        this.getSelectData('post', this.lib.config.host.masterData + '/mdata/purOrgMgt/purGroup/getByPurOrgId/' + value, {}, 'id', 'purGroupName').then((data)=>{
            this.relationPurGroup = data;
        });
        // 获取采购组织对应的工厂
        this.getSelectData('post', this.lib.config.host.masterData + '/system/factoryMgt/factorys/getFactoryByPurId/' + value, {}, 'id', 'factoryName').then((data)=>{
            this.relationFactory = data;
        });
      },
      // 获取选中的数据
      getCheckedData(data){
        this.checkedData = data;
      },
      // 打开关闭对话框
      openCloseDialog(){
        this.dialogVisible = true;
      },
      // 关闭采购申请
      closePrItem(){
        let isRequest = true;
        if(this.checkedData.length <= 0){
          this.$message({
            type:'warning',
            message:'请选择记录进行关闭!'
          })
        } else {
          // 声明一个有效的id数组集合
          let ids = [];
          this.checkedData.map(item =>{
            if(item.closeStatus === 1){
              this.$message({
                type:'warning',
                message:'申请单号:' + item.srmPrNo + '行号:' + item.srmItemNo + ',已关闭无法重复关闭！'
              })
              return isRequest = false;
            }
            // 已处理，无法关闭
            if(item.handleStatus === 1){
              this.$message({
                type:'warning',
                message:'申请单号:' + item.srmPrNo + '行号:' + item.srmItemNo + ',已处理无法关闭！'
              })
              return isRequest = false;
            }
            this.ids.push(item.id);
          });
          if(isRequest){ //是否发起请求
            this.closeForm.ids = this.ids;
            this.axios.post('', ids)
            .then((res) =>{
              if(res.data.success){
                this.$message({
                  type:'success',
                  message:'关闭成功！'
                })
              } else {
                this.$message({
                  type:'error',
                  message: res.data.message
                })
              }
            })
            .catch((error)=>{
              this.$message({
                type: 'error',
                message: error
              });
            });
          }
        }
      },
      // 取消对话框
      cancleDialog(formObj){
        this.resetForm(formObj);
        this.dialogVisible = false;
      },
      // 打开待处理对话框
      openPendingDialog(){
        this.pendingVisible = true;
      },
      handleClick(type) {
        switch(type){
          case "1" :
            alert('订单！')
            break;
          case "2" :
            this.toEnquiry(); // 转询价
            break;
          case "3":
            this.toBid();
            break;
          case "4":
            this.toNpcTask()
            break;
        }
      },
      // 加入到待询价清单里
      addToEnquiry(){
       if(this.checkedData.length <= 0){
          this.$message({
            type: 'warning',
            message: '请选择数据!'
          });
       }  else {
          this.checkedData.forEach((element1)=>{
            let isContain = false;
            let isAllow = true;
            if(this.pendingData.length > 0){
              this.pendingData.forEach((element2)=>{
                if(element2.factoryId !== element1.factoryId && element2.purGroupId !== element1.purGroupId){ // 过滤不同工厂和采购组数据
                  isAllow = false;
                  return;
                }
                if(element2.prNo === element1.prNo && element2.itemNo === element1.itemNo){ // 过滤重复加入数据
                  isContain = true;
                  return;
                }
              })
            }
            if(!isContain && isAllow){
              this.pendingData.push(element1);
              this.pendingCount = this.pendingData.length;
            }
          })
        }
      },
      // 转询比价
      toEnquiry(){
        // 转物料认证页面
        let validateResult = this.turnBeforValidateResult();
        if(validateResult){ // 验证通过方可执行
        axios.all([this.loadMaterials(), this.loadVendors()])
          .then(axios.spread((acct, perms)=> {
            // 两个请求现在都执行完成
            this.$router.push({path: '/Index/Rfq/AddRfqEnquiry', query:{'routerSource':'prRequest','materialData': this.materialData,'vendorData': this.vendorData}})
          }));
        }
      },
      // 转招标
      toBid(){
        // 转物料认证页面
        let validateResult = this.turnBeforValidateResult();
        if(validateResult){ // 验证通过方可执行
          this.loadMaterials();
          this.loadVendors();
          this.$confirm('确认发起招标嘛？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push({name:'creatBid', query:{'routerSource':'prRequest','materialData': this.materialData,'vendorData': this.vendorData}});
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消操作!'
            });
          });
        }
      },
      // 页面初始化加载物料
      loadMaterials() {
        this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/toEnquiry/loadMaterials',this.selectedIdArry)
        .then((res)=>{
          if(res.data.success){
            this.materialData = res.data.result;
          }
        })
        .catch((error)=>{
          console.log(error);
        })
      },
      // 页面初始化加载供应商
      loadVendors() {
        this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/toEnquiry/loadVendors', this.selectedIdArry)
        .then((res)=>{
          if(res.data.success){
            this.vendorData = res.data.result;
          }
        })
        .catch((error)=>{
          console.log(error);
        })
      },
      // 转物料认证
      toNpcTask(){
        //this.$router.push({name:'AddNpcTaskTab'});
        // 转物料认证页面
        let validateResult = this.turnBeforValidateResult();
        if(validateResult){ // 验证通过方可执行
          this.$confirm('确认转物料认证嘛？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push({path: '/Index/VendorDlv/Npc/Buyer/Withmtrl/Add/Tab', query:{'checkedData': this.checkedData}})
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消操作!'
            });
          });
        }
      },
      // 跳转前数据可行性验证
      turnBeforValidateResult() {
        let validateResult = true;
        if(this.checkedData.length <= 0){
          this.$message({
            type: 'warning',
            message: '请选择数据!'
          });
          return validateResult = false;
        } else {
          const purGroupId = this.checkedData[0].purGroupId;
          const factoryId = this.checkedData[0].factoryId;
          this.checkedData.forEach(element =>{
            // 数据采购组需保持一致
            if(purGroupId != element.purGroupId){
              this.$message({
                type: 'warning',
                message: '采购组选择不一致，请筛选数据!'
              });
              return validateResult = false;
            }
            // 数据品类需保持一致
            if(factoryId != element.factoryId){
              this.$message({
                type: 'warning',
                message: '工厂选择不一致，请筛选数据!'
              });
              return validateResult = false;
            }  
            this.selectedIdArry.push(element.id);
          })
        }
        return validateResult;
      }
    }
  }
</script>